package com.yzc.android.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

import java.util.List;

import com.yzc.android.KDApp;
import com.yzc.android.beans.BeaconBean;
import com.yzc.android.manager.ibeacon.IBeaconScanManager;
import com.yzc.android.manager.ibeacon.ScanCallback;
import com.yzc.android.manager.ibeacon.ScanResult;
import com.yzc.android.manager.sensor.ESSensorManager;
import com.yzc.android.manager.sensor.config.pull.PullSensorConfig;
import com.yzc.android.manager.sensor.sensors.SensorUtils;
import com.yzc.android.receiver.WakeReceiver;
import com.yzc.android.ui.SensorsThread;
import com.yzc.android.utils.LogUtils;
import com.yzc.android.utils.PreferencesUtils;
import com.yzc.android.utils.ToastUtil;

/**
 * Created by yzc on 16/5/24.
 */
public class AlgorithmicAliveService extends Service/* implements BeaconScanManagerListener*/ {

    /**
     * 定时唤醒的时间间隔，5分钟
     */
    private final static int ALARM_INTERVAL = 5 * 60 * 1000;
    private final static int WAKE_REQUEST_CODE = 6666;
    private final static int GRAY_SERVICE_ID = 1001;

    public final static String ALIVE_SERVICE_TAG = "alive_service";

    private boolean mIsInRegion = false;

    private Handler mHandler = new Handler();

    // 业务相关
    private ESSensorManager mSensorManager;

    private SensorsThread mAccelerometerSensorThread;

    private SensorsThread mGyroscopeSensorThread;

    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(final int callbackType, final ScanResult result) {
            super.onScanResult(callbackType, result);
            LogUtils.d(ALIVE_SERVICE_TAG, "single beaconBean(%s)", result);
        }

        @Override
        public void onBatchScanResults(final List<ScanResult> results) {
            super.onBatchScanResults(results);

            if (results.size() <= 0) {
                LogUtils.d(ALIVE_SERVICE_TAG, "beacon onExited region");
                ToastUtil.getInstance().showToast("您离开了热点区域");
                mIsInRegion = false;

                //if (mAccelerometerSensorThread != null) {
                //    mAccelerometerSensorThread.stopSensing();
                //}

                //if (mGyroscopeSensorThread != null) {
                //    mGyroscopeSensorThread.stopSensing();
                //}

                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction(KDApp.mBroadcastIBeaconExitAction);
                sendBroadcast(broadcastIntent);
            }
            else {
                boolean found = false;
                BeaconBean theBeacon = null;
                for (ScanResult scanResult : results) {
                    BeaconBean beaconBean = scanResult.getBeaconBean();
                    if (beaconBean == null) continue;
                    //LogUtils.d(ALIVE_SERVICE_TAG, "multi beaconBean(%s)", beaconBean);
                    found = beaconBean.proximityUuid.equals(PreferencesUtils.getString(AlgorithmicAliveService.this, IBeaconScanManager.PRE_KEY_IBEACON_UUID, "11111111-2222-2222-2222-111111111113"))
                            && beaconBean.major == PreferencesUtils.getInt(AlgorithmicAliveService.this, IBeaconScanManager.PRE_KEY_IBEACON_MAJOR, 10002)
                            && beaconBean.minor == PreferencesUtils.getInt(AlgorithmicAliveService.this, IBeaconScanManager.PRE_KEY_IBEACON_MINOR, 5208);
                    if (found) {
                        theBeacon = beaconBean;
                        break;
                    }
                }

                if (found) {
                    if (!mIsInRegion) {
                        ToastUtil.getInstance().showToast("您进入了热点区域");
                        LogUtils.d(ALIVE_SERVICE_TAG, "beacon onEntered region");
                        mIsInRegion = true;

                        if (mAccelerometerSensorThread != null) {
                            mAccelerometerSensorThread.startSensing();
                        }

                        if (mGyroscopeSensorThread != null) {
                            mGyroscopeSensorThread.startSensing();
                        }

                        Intent broadcastIntent = new Intent();
                        broadcastIntent.setAction(KDApp.mBroadcastIBeaconEnterAction);
                        broadcastIntent.putExtra("Data", theBeacon);
                        sendBroadcast(broadcastIntent);
                    }
                }
                else {
                    if (mIsInRegion) {
                        ToastUtil.getInstance().showToast("您离开了热点区域");
                        LogUtils.d(ALIVE_SERVICE_TAG, "beacon onExited region");
                        mIsInRegion = false;

                        //if (mAccelerometerSensorThread != null) {
                        //    mAccelerometerSensorThread.stopSensing();
                        //}

                        //if (mGyroscopeSensorThread != null) {
                        //    mGyroscopeSensorThread.stopSensing();
                        //}

                        Intent broadcastIntent = new Intent();
                        broadcastIntent.setAction(KDApp.mBroadcastIBeaconExitAction);
                        sendBroadcast(broadcastIntent);
                    }
                }
            }
        }

        @Override
        public void onScanFailed(final int errorCode) {
            super.onScanFailed(errorCode);
        }
    };

    @Override
    public void onCreate() {
        LogUtils.i(ALIVE_SERVICE_TAG, "AlgorithmicAliveService->onCreate");
        super.onCreate();

        //initSensors();
        //BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        //ScanSettings settings = new ScanSettings.Builder()
        //        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(2*1000)
        //        .setUseHardwareBatchingIfSupported(false).build();
        ////scanner.stopScan(mScanCallback);
        //scanner.startScan(null, settings, mScanCallback);
        //if (mAccelerometerSensorThread != null) {
        //    mAccelerometerSensorThread.startSensing();
        //}
        //
        //if (mGyroscopeSensorThread != null) {
        //    mGyroscopeSensorThread.startSensing();
        //}
        //
        //mHandler.postDelayed(new Runnable() {
        //    @Override
        //    public void run() {
        //        if (mAccelerometerSensorThread != null) {
        //            mAccelerometerSensorThread.stopSensing();
        //        }
        //        if (mGyroscopeSensorThread != null) {
        //            mGyroscopeSensorThread.stopSensing();
        //        }
        //        FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant.kAccelerometerLogTag),
        //                                LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant.kAccelerometerLogTag));
        //        FileUtils.zipFileAtPath(LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileName(SensorConstant.kGyroscopeLogTag),
        //                                LogUtils.LOCAL_DEBUG_LOG_FOLDER+LogUtils.generateFileZipName(SensorConstant.kGyroscopeLogTag));
        //        ToastUtil.getInstance().showToast("压缩记录完成");
        //    }
        //}, 2*60*1000);
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.i(ALIVE_SERVICE_TAG, "AlgorithmicAliveService->onBind");
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        LogUtils.i(ALIVE_SERVICE_TAG, "AlgorithmicAliveService->onDestroy");
        super.onDestroy();
        if (mAccelerometerSensorThread != null) {
            mAccelerometerSensorThread.stopSensing();
        }
        if (mGyroscopeSensorThread != null) {
            mGyroscopeSensorThread.stopSensing();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.i(ALIVE_SERVICE_TAG, "AlgorithmicAliveService->onStartCommand");
        mIsInRegion = false;

        if (Build.VERSION.SDK_INT < 18) {
            startForeground(GRAY_SERVICE_ID, new Notification());//API < 18 ，此方法能有效隐藏Notification上的图标
        } else {
            Intent innerIntent = new Intent(this, AlgorithmicAliveInnerService.class);
            startService(innerIntent);
            startForeground(GRAY_SERVICE_ID, new Notification());
        }

        //发送唤醒广播来促使挂掉的UI进程重新启动起来
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent();
        alarmIntent.setAction(WakeReceiver.GRAY_WAKE_ACTION);
        PendingIntent operation = PendingIntent.getBroadcast(this, WAKE_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ALARM_INTERVAL, operation);

        return START_STICKY;
    }

    private void initSensors() {
        LogUtils.i(ALIVE_SERVICE_TAG, "AlgorithmicAliveService->initSensors");
        try {
            if (mSensorManager == null) {
                mSensorManager = ESSensorManager.getSensorManager(AlgorithmicAliveService.this);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_ACCELEROMETER,
                                               PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_ACCELEROMETER,
                                               PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_GYROSCOPE, PullSensorConfig.POST_SENSE_SLEEP_LENGTH_MILLIS, 1000L);
                mSensorManager.setSensorConfig(SensorUtils.SENSOR_TYPE_GYROSCOPE, PullSensorConfig.SENSE_WINDOW_LENGTH_MILLIS, 1000L);
            }

            if (mAccelerometerSensorThread == null) {
                mAccelerometerSensorThread = new SensorsThread(AlgorithmicAliveService.this, mSensorManager,
                                                               SensorUtils.SENSOR_TYPE_ACCELEROMETER);
            }

            if (mGyroscopeSensorThread == null) {
                mGyroscopeSensorThread = new SensorsThread(AlgorithmicAliveService.this, mSensorManager, SensorUtils.SENSOR_TYPE_GYROSCOPE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 给 API >= 18 的平台上用的灰色保活手段
     */
    public static class AlgorithmicAliveInnerService extends Service {
        @Override
        public void onCreate() {
            //LogUtils.i(ALIVE_SERVICE_TAG, "InnerAliveService->onCreate");
            super.onCreate();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //LogUtils.i(ALIVE_SERVICE_TAG, "InnerAliveService->onStartCommand");
            startForeground(GRAY_SERVICE_ID, new Notification());
            //stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }

        @Override
        public void onDestroy() {
            //LogUtils.i(ALIVE_SERVICE_TAG, "InnerAliveService->onDestroy");
            super.onDestroy();
        }
    }
}
